package com.xiaolei.lib.annotation.translators;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.xiaolei.lib.Activity.IActivity;
import com.xiaolei.lib.Activity.bean.AnnotationWrape;
import com.xiaolei.lib.annotation.setOnItemClick;
import com.xiaolei.lib.core.ITranslator;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;


/**
 * ListView的Item点击事件
 * @author xiaolei
 */
public class setOnItemClickTranslator implements ITranslator
{
	@Override
	public void execute(Field field, IActivity activity, AnnotationWrape annotation)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void execute(final Method method, final IActivity activity, AnnotationWrape annotation)
	{
		setOnItemClick sItemClick = annotation.get(setOnItemClick.class);
		int id = sItemClick.value();
		View view = activity.findViewByID(id);
		if(AdapterView.class.isInstance(view))
		{
			AdapterView<?> listView = (AdapterView<?>) view;
			listView.setOnItemClickListener(new OnItemClickListener()
			{
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id)
				{
					Class<?> types[] = method.getParameterTypes();
					Object args[] = new Object[types.length];
					Object posBean = parent.getAdapter().getItem(position);
					for (int i = 0;i<types.length;i++)
					{
						Class<?> paramType = types[i];
						if(paramType.isInstance(parent))
						{
							args[i] = parent;
						}else if (paramType.isInstance(view)) 
						{
							args[i] = view;
						}else if (paramType == int.class || paramType == Integer.class) 
						{
							args[i] = position;
						}else if (paramType == long.class || paramType == Long.class) 
						{
							args[i] = id;
						}else if(paramType.isInstance(posBean))  // 可以直接写自定义的bean
						{
							args[i] = posBean;
						}
					}
					try
					{
						if(!method.isAccessible())
							method.setAccessible(true);
						method.invoke(activity, args);
					} catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			});
		}
	}

	@Override
	public void execute(Class<?> type, IActivity activity, AnnotationWrape annotation)
	{
		// TODO Auto-generated method stub

	}

}
